/**
 * 
 */
requirejs.config({
    baseUrl:'http://static.auoffice.com/static/js' ,
    waitSeconds: 0,
    paths: {
    	jquery:'libs/jquery.min',
        datatables: 'libs/dataTables/jquery.dataTables.min',
        btdatatables: 'libs/dataTables/dataTables.bootstrap.min',
        //plugins
        base: 'common/base',
    },
    shim: {
        'datatables': {
            deps: ['jquery'],
            exports: 'datatables'
        },
        'btdatatables': {
            deps: ['jquery'],
            exports: 'btdatatables'
        }, 
    }
});

require([
    'jquery',
 	'common/base',
 	'datatables',
 	'btdatatables'
],function($,base) {
    var table = $("#data_table").DataTable({
        "searching": true,
        "processing": true,
        "serverSide": true,
        "ordering": false,
        "deferRender": true,
        "ajax": {
            "url": '/funcresource/userfunctional/list/',
            "type": "POST"
        },
        "columnDefs": [
           {
               "targets": 0,
               "data": null,
               "name": null,
               "searchable": false,
               "bSortable": false,
               "render": function (data, type, full) {
                   var html = '<input style="width:18px;height:18px" type="checkbox" name="userfunctional_id" data-state="'+full.state+'" data-id="'+full.id+'"/>';
                   return html;
               }
            },
            {
                "targets": 1,
                "data": "username",
                "name": "username",
                "searchable": false,
                "bSortable": false
            },
            {
            	"targets": 2,
            	"data": "func_name",
            	"name": "func_name",
            	"searchable": false,
            	"bSortable": false
            },
            {
            	"targets": 3,
            	"data": "func_resource_name",
            	"name": "func_resource_name",
            	"searchable": false,
            	"bSortable": false
            },
            {
            	"targets": 4,
            	"data": "state_desc",
            	"name": "state_desc",
            	"searchable": false,
            	"bSortable": false
            }
        ],
        "initComplete": function () {
            var api = this.api();
            var column = api.column(4);
            var select = $('<select class="form-control" id="_status"><option value="">--状态--</option></select>')
            .appendTo($(column.header()).empty() )
            .on( 'change', function (){
                var val = $.fn.dataTable.util.escapeRegex(
                    $(this).val()
                );
                $("#all").prop("checked",false);
                column.search( val ? '^'+val+'$' : '', true, false ).draw();
            });
            select.append(_state());
        },
        "oLanguage": {
            "sLengthMenu": '每页显示 _MENU_条 &nbsp;',
            "sZeroRecords": "没有找到符合条件的数",
            "sProcessing": "加载中...",
            "sInfo": "当前第 _START_ - _END_ 条　共计 _TOTAL_ 条",
            "sInfoEmpty": "木有记录",
            "sInfoFiltered": "(从 _MAX_ 条记录中过滤)",
            "sSearch": "搜索：",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "«",
                "sNext": "»",
                "sLast": "尾页"
            }
        }
    });
    var _state = function() {
        return  '<option value="0">有效</option><option value="9">删除</option>';
    };
    
    //datatables 行点击事件
    $("#data_table tbody").on('click','tr', function () {
    	var checked = $("td",this).find("input[type=checkbox]");
    	if ($(checked).is(':checked')){
    		$(checked).prop("checked",false);
    	}else{
    		$(checked).prop("checked",true);
    	}
    	var tr_len = $("#data_table tbody tr").find("input[type=checkbox]").length;
    	var check_len = $("#data_table tbody tr").find("input[type=checkbox]:checked").length;
    	if (tr_len == check_len){
    		$("#all").prop("checked",true);
    	}else{
    		$("#all").prop("checked",false);
    	}
    });
    
    //datatables 全选事件
    $("#all").click(function(){
    	if ($(this).is(':checked')){
    		$("#data_table tbody tr").find("input[type=checkbox]").prop("checked",true);
    	}else{
    		$("#data_table tbody tr").find("input[type=checkbox]").prop("checked",false);
    	}
    });
    
    $(".delete").click(function(){
    	var len = $("[name=userfunctional_id]:checked").length;
    	if (len <= 0){
    		base.layui.alert("信息","请选择数据");
    		return;
    	}
    	var _userfunctional_ids = []
    	var is_valid = false;
    	$("[name=userfunctional_id]:checked").each(function(){
    		if($(this).attr("data-state") != 0){
    			is_valid = true;
    			return false;
    		}
    		_userfunctional_ids.push($(this).attr("data-id"));
    	});
    	if(is_valid){
    		base.layui.alert("提示信息","请选择有效的记录");
    		return;
    	}
    	base.layui.confirm('警告', '确认删除选中的记录',{"_userfunctional_ids":_userfunctional_ids}, _delCallback);
    });
    var _delCallback = function(arg){
    	base.services.post('funcresource', 'deleteUserFunctional', {"userfunctional_ids":arg._userfunctional_ids.join(",")}, function(code, msg, data) {
    		if (code === base.services.CODE_SUCC) {
    			base.layui.alert("成功信息","删除成功",callback);
    		} else {
    			base.layui.alert("错误信息",msg);
    		}
    	});
    };
    $(".reopen").click(function(){
    	var len = $("[name=userfunctional_id]:checked").length;
    	if (len <= 0){
    		base.layui.alert("信息","请选择数据");
    		return;
    	}
    	var _userfunctional_ids = [];
    	var is_valid = false;
    	$("[name=userfunctional_id]:checked").each(function(){
    		if($(this).attr("data-state") != 9){
    			is_valid = true;
    			return false;
    		}
    		_userfunctional_ids.push($(this).attr("data-id"));
    	});
    	if(is_valid){
    		base.layui.alert("提示信息","请选择删除的记录");
    		return;
    	}
    	base.layui.confirm('警告', '确认重新开通选中的记录',{"_userfunctional_ids":_userfunctional_ids}, _reopenCallback);
    });
    var _reopenCallback = function(arg){
    	base.services.post('funcresource', 'reopenUserFunctional', {"userfunctional_ids":arg._userfunctional_ids.join(",")}, function(code, msg, data) {
    		if (code === base.services.CODE_SUCC) {
    			base.layui.alert("成功信息","重新开通成功",callback);
    		} else {
    			base.layui.alert("错误信息",msg);
    		}
    	});
    };
	var callback = function(){
		table.draw();
	}
});